package com.seqb.common.utils;

import com.alibaba.fastjson.JSON;
import com.seqb.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2019/11/28
 */
public class ReptileUtils {

    //获取文档内容
    public Document getDocument(String url) {
        try {
            //5000是设置连接超时时间，单位ms
            return Jsoup.connect(url).timeout(5000).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //测试获取天气的信息
    public void testGetWeather() {
        ReptileUtils reptileUtils = new ReptileUtils();
        Document doc = reptileUtils.getDocument("http://www.weather.com.cn/weather/101281701.shtml");

        // 获取目标HTML代码
        Elements elements1 = doc.select("[class=t clearfix]");

        //今天
        Elements elements2 = elements1.select("[class=sky skyid lv1 on]");
        String today = elements2.get(0).text();
        System.out.println("今日天气： " + today);

        //几号
        Elements elements3 = elements1.select("h1");
        String number = elements3.get(0).text();
        System.out.println("日期： " + number);

        // 天气
        Elements elements4 = elements1.select("[class=wea]");
        String rain = elements4.get(0).text();
        System.out.println("天气： " + rain);

        // 最高温度
        Elements elements5 = elements1.select("span");
        String highTemperature = elements5.get(0).text() + "°C";
        System.out.println("最高温：" + highTemperature);

        // 最低温度
        Elements elements6 = elements1.select(".tem i");
        String lowTemperature = elements6.get(0).text();
        System.out.println("最低温：" + lowTemperature);

        // 风力
        Elements elements7 = elements1.select(".win i");
        String wind = elements7.get(2).text();
        System.out.println("风力：" + wind);
    }

    //测试获取信管网的试题（选择题）
    public static List testGetXgwXztQuestion(String url) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }

        List questionList = new ArrayList<>();
        Map<String, Object> itemMap = new HashMap<>();

        ReptileUtils reptileUtils = new ReptileUtils();
        Document doc = reptileUtils.getDocument(url);
        // 获取目标HTML代码
        Elements elements1 = doc.select("table[width=950]");

        for (int i = 1; i < elements1.size(); i++) {
            Element table = elements1.get(i);
            Element tr = table.select("tr").first();
            Element td = tr.select("td").first();
            Element img = tr.select("img").first();

            Elements imgs = tr.select("img");

            String text = td.text().trim();
            if (text.indexOf("第") < 0 || text.indexOf("题") < 0) {
                continue;
            }
            System.out.println(text);

            String number = text.split("：")[0].trim();
            number = number.replace("第", "").replace("题", "");
            System.out.println(number);

            //一题包含了两小题
            if (number.indexOf("、") > 0) {
                String name = "";
                String options = "";
                if (text.lastIndexOf("。") > 0) {
                    name = text.substring(text.indexOf("：") + 2, text.lastIndexOf("。")).trim();
                    options = text.substring(text.indexOf("。"));
                } else if (text.lastIndexOf("（2）") > 0) {
                    name = text.substring(text.indexOf("：") + 2, text.lastIndexOf("（2）")).trim();
                    options = text.substring(text.indexOf("（2）") + 3);
                } else if (text.lastIndexOf("(2)") > 0) {
                    name = text.substring(text.indexOf("：") + 2, text.indexOf("(2)")).trim();
                    options = text.substring(text.indexOf("(2)") + 3);
                }
                if (name.substring(name.length() - 1).equals(".")) {
                    name = name.substring(0, name.length() - 1) + "。";
                }
                if (!name.substring(name.length() - 1).equals("。")) {
                    name = name + "。";
                }
                System.out.println(name);
                System.out.println(options);

                String optionA = "";
                String optionB = "";
                String optionC = "";
                if (text.indexOf("A、") > 0) {
                    optionA = options.substring(options.indexOf("A、") + 2, options.indexOf("B、")).trim();
                    optionB = options.substring(options.indexOf("B、") + 2, options.indexOf("C、")).trim();
                    optionC = options.substring(options.indexOf("C、") + 2, options.indexOf("D、")).trim();
                } else if (text.indexOf("A.") > 0) {
                    optionA = options.substring(options.indexOf("A.") + 2, options.indexOf("B.")).trim();
                    optionB = options.substring(options.indexOf("B.") + 2, options.indexOf("C.")).trim();
                    optionC = options.substring(options.indexOf("C.") + 2, options.indexOf("D.")).trim();
                } else if (text.indexOf("A．") > 0) {
                    optionA = options.substring(options.indexOf("A．") + 2, options.indexOf("B．")).trim();
                    optionB = options.substring(options.indexOf("B．") + 2, options.indexOf("C．")).trim();
                    optionC = options.substring(options.indexOf("C．") + 2, options.indexOf("D．")).trim();
                }

                String optionD = "";
                if (options.lastIndexOf("(2)") > 0) {
                    if (text.indexOf("A、") > 0) {
                        optionD = options.substring(options.indexOf("D、") + 2, options.lastIndexOf("(2)")).trim();
                    } else if (text.indexOf("A.") > 0) {
                        optionD = options.substring(options.indexOf("D.") + 2, options.lastIndexOf("(2)")).trim();
                    } else if (text.indexOf("A．") > 0) {
                        optionD = options.substring(options.indexOf("D．") + 2, options.lastIndexOf("(2)")).trim();
                    }
                } else if (options.lastIndexOf("（") > 0) {
                    if (text.indexOf("A、") > 0) {
                        optionD = options.substring(options.indexOf("D、") + 2, options.lastIndexOf("（")).trim();
                    } else if (text.indexOf("A.") > 0) {
                        optionD = options.substring(options.indexOf("D.") + 2, options.lastIndexOf("（")).trim();
                    } else if (text.indexOf("A．") > 0) {
                        optionD = options.substring(options.indexOf("D．") + 2, options.lastIndexOf("（")).trim();
                    }
                } else if (options.lastIndexOf("(") > 0) {
                    if (text.indexOf("A、") > 0) {
                        optionD = options.substring(options.indexOf("D、") + 2, options.lastIndexOf("(")).trim();
                    } else if (text.indexOf("A.") > 0) {
                        optionD = options.substring(options.indexOf("D.") + 2, options.lastIndexOf("(")).trim();
                    } else if (text.indexOf("A．") > 0) {
                        optionD = options.substring(options.indexOf("D．") + 2, options.lastIndexOf("(")).trim();
                    }
                }
                System.out.println(optionA);
                System.out.println(optionB);
                System.out.println(optionC);
                System.out.println(optionD);

                Map optionMap = new HashMap();
                optionMap.put("A", optionA);
                optionMap.put("B", optionB);
                optionMap.put("C", optionC);
                optionMap.put("D", optionD);
                itemMap = new HashMap<>();
                itemMap.put("sortNumber", number.split("、")[0]);
                String renameStr = name.replaceFirst("（）", "（请作答此空）");
                renameStr = renameStr.replaceFirst("（1）", "（请作答此空）");
                renameStr = renameStr.replaceFirst("（ 1 ）", "（请作答此空）");
                itemMap.put("name", renameStr);
                itemMap.put("type", "1");
                if (null != img) {
                    itemMap.put("img", img.attr("src"));
                }
                itemMap.put("choiceOption", JsonUtils.beanToJson(optionMap));
                questionList.add(itemMap);


                if (text.indexOf("A、") > 0) {
                    optionA = options.substring(options.indexOf("A、", options.lastIndexOf("A、")) + 2, options.indexOf("B、", options.lastIndexOf("A、"))).trim();
                    optionB = options.substring(options.indexOf("B、", options.lastIndexOf("A、")) + 2, options.indexOf("C、", options.lastIndexOf("A、"))).trim();
                    optionC = options.substring(options.indexOf("C、", options.lastIndexOf("A、")) + 2, options.indexOf("D、", options.lastIndexOf("A、"))).trim();
                    optionD = options.substring(options.indexOf("D、", options.lastIndexOf("A、")) + 2).trim();
                } else if (text.indexOf("A.") > 0) {
                    optionA = options.substring(options.indexOf("A.", options.lastIndexOf("A.")) + 2, options.indexOf("B.", options.lastIndexOf("A."))).trim();
                    optionB = options.substring(options.indexOf("B.", options.lastIndexOf("A.")) + 2, options.indexOf("C.", options.lastIndexOf("A."))).trim();
                    optionC = options.substring(options.indexOf("C.", options.lastIndexOf("A.")) + 2, options.indexOf("D.", options.lastIndexOf("A."))).trim();
                    optionD = options.substring(options.indexOf("D.", options.lastIndexOf("A.")) + 2).trim();

                    optionA = options.substring(options.indexOf("A.") + 2, options.indexOf("B.")).trim();
                    optionB = options.substring(options.indexOf("B.") + 2, options.indexOf("C.")).trim();
                    optionC = options.substring(options.indexOf("C.") + 2, options.indexOf("D.")).trim();
                } else if (text.indexOf("A．") > 0) {
                    optionA = options.substring(options.indexOf("A．", options.lastIndexOf("A．")) + 2, options.indexOf("B．", options.lastIndexOf("A．"))).trim();
                    optionB = options.substring(options.indexOf("B．", options.lastIndexOf("A．")) + 2, options.indexOf("C．", options.lastIndexOf("A．"))).trim();
                    optionC = options.substring(options.indexOf("C．", options.lastIndexOf("A．")) + 2, options.indexOf("D．", options.lastIndexOf("A．"))).trim();
                    optionD = options.substring(options.indexOf("D．", options.lastIndexOf("A．")) + 2).trim();
                }
                System.out.println(optionA);
                System.out.println(optionB);
                System.out.println(optionC);
                System.out.println(optionD);

                optionMap = new HashMap();
                optionMap.put("A", optionA);
                optionMap.put("B", optionB);
                optionMap.put("C", optionC);
                optionMap.put("D", optionD);
                itemMap = new HashMap<>();
                itemMap.put("sortNumber", number.split("、")[1]);
                StringBuilder rename = new StringBuilder(name);
                if (name.lastIndexOf("（）") > 0) {
                    rename.replace(name.lastIndexOf("（）"), name.lastIndexOf("（）") + 2, "（请作答此空）");
                }
                if (name.lastIndexOf("（2）") > 0) {
                    rename.replace(name.lastIndexOf("（2）"), name.lastIndexOf("（2）") + 3, "（请作答此空）");
                }
                if (name.lastIndexOf("（ 2 ）") > 0) {
                    rename.replace(name.lastIndexOf("（ 2 ）"), name.lastIndexOf("（ 2 ）") + 5, "（请作答此空）");
                }
                itemMap.put("name", rename.toString());
                itemMap.put("type", "1");
                if (null != img) {
                    itemMap.put("img", img.attr("src"));
                }
                itemMap.put("choiceOption", JsonUtils.beanToJson(optionMap));
                questionList.add(itemMap);
            }

            //1张图片含所有选项
            else if (text.indexOf("A、") < 0 && imgs.size() >= 1 && text.indexOf("A．") < 0) {
                String name = text;
                Map optionMap = new HashMap();
                optionMap.put("option", imgs.get(imgs.size() - 1).attr("src"));
                itemMap = new HashMap<>();
                itemMap.put("sortNumber", number);
                itemMap.put("name", name);
                itemMap.put("type", "1");
                if (null != img) {
                    itemMap.put("img", img.attr("src"));
                }
                itemMap.put("choiceOption", JsonUtils.beanToJson(optionMap));
                itemMap.put("optionType", "3");
                questionList.add(itemMap);
            }

            //1张图片含1个选项(4张)
            else if (text.indexOf("A、") > 0 && imgs.size() >= 4 && text.indexOf("A．") < 0) {
                String name = text;
                String optionA = imgs.get(imgs.size() - 1).attr("src");
                String optionB = imgs.get(imgs.size() - 2).attr("src");
                String optionC = imgs.get(imgs.size() - 3).attr("src");
                String optionD = imgs.get(imgs.size() - 4).attr("src");

                Map optionMap = new HashMap();
                optionMap.put("A", optionA);
                optionMap.put("B", optionB);
                optionMap.put("C", optionC);
                optionMap.put("D", optionD);
                itemMap = new HashMap<>();
                itemMap.put("sortNumber", number);
                itemMap.put("name", name);
                itemMap.put("type", "1");
                if (null != img) {
                    itemMap.put("img", img.attr("src"));
                }
                itemMap.put("choiceOption", JsonUtils.beanToJson(optionMap));
                itemMap.put("optionType", "2");
                questionList.add(itemMap);
            }

            //有逗号可以隔开题目和选项
            else {
                String name = "";
                String optionA = "";
                String optionB = "";
                String optionC = "";
                String optionD = "";
                if (text.indexOf("A、") > 0) {
                    name = text.substring(text.indexOf("：") + 2, text.indexOf("A、")).trim();
                    String options = text.substring(text.indexOf("A、"));
                    optionA = options.substring(options.indexOf("A、") + 2, options.indexOf("B、")).trim();
                    optionB = options.substring(options.indexOf("B、") + 2, options.indexOf("C、")).trim();
                    optionC = options.substring(options.indexOf("C、") + 2, options.indexOf("D、")).trim();
                    optionD = options.substring(options.indexOf("D、") + 2).trim();
                } else if (text.indexOf("A.") > 0) {
                    name = text.substring(text.indexOf("：") + 2, text.indexOf("A.")).trim();
                    String options = text.substring(text.indexOf("A."));
                    optionA = options.substring(options.indexOf("A.") + 2, options.indexOf("B.")).trim();
                    optionB = options.substring(options.indexOf("B.") + 2, options.indexOf("C.")).trim();
                    optionC = options.substring(options.indexOf("C.") + 2, options.indexOf("D.")).trim();
                    optionD = options.substring(options.indexOf("D.") + 2).trim();
                } else if (text.indexOf("A．") > 0) {
                    name = text.substring(text.indexOf("：") + 2, text.indexOf("A．")).trim();
                    String options = text.substring(text.indexOf("A．"));
                    optionA = options.substring(options.indexOf("A．") + 2, options.indexOf("B．")).trim();
                    optionB = options.substring(options.indexOf("B．") + 2, options.indexOf("C．")).trim();
                    optionC = options.substring(options.indexOf("C．") + 2, options.indexOf("D．")).trim();
                    optionD = options.substring(options.indexOf("D．") + 2).trim();
                }

                if (name.substring(name.length() - 1).equals(".")) {
                    name = name.substring(0, name.length() - 1) + "。";
                }
                if (!name.substring(name.length() - 1).equals("。")) {
                    name = name + "。";
                }
                System.out.println(name);
                System.out.println(optionA);
                System.out.println(optionB);
                System.out.println(optionC);
                System.out.println(optionD);

                Map optionMap = new HashMap();
                optionMap.put("A", optionA);
                optionMap.put("B", optionB);
                optionMap.put("C", optionC);
                optionMap.put("D", optionD);
                itemMap = new HashMap<>();
                itemMap.put("sortNumber", number);
                itemMap.put("name", name);
                itemMap.put("type", "1");
                if (null != img) {
                    itemMap.put("img", img.attr("src"));
                }
                itemMap.put("choiceOption", JsonUtils.beanToJson(optionMap));
                questionList.add(itemMap);
            }
            System.out.println("---------------------" + i + "----------------------");

        }

        return questionList;
    }

    //测试获取信管网的试题（案例分析）
    public static String testGetXgwAlfxQuestion(String url) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }

        ReptileUtils reptileUtils = new ReptileUtils();
        Document doc = reptileUtils.getDocument(url);
        Elements elements1 = doc.select("table[width=950]");
        for (int i = 1; i < elements1.size(); i++) {
            Element table = elements1.get(i);
            Element tr = table.select("tr").first();
            Element td = tr.select("td").first();
            Element font = td.select("font[color=#FF0000]").first();
            font.removeAttr("color");
            System.out.println(td.html().toString());
            return td.html().toString();
        }
        return null;
    }

    //测试获取信管网的试题（论文）
    public static String testGetXgwLwQuestion(String url) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }
        ReptileUtils reptileUtils = new ReptileUtils();
        Document doc = reptileUtils.getDocument(url);
        Elements elements1 = doc.select("div.newcon");
        for (int i = 0; i < elements1.size(); i++) {
            Element div = elements1.get(i);
            System.out.println(div.html().toString());
            return div.outerHtml().toString();
        }
        return null;
    }

    //测试获取信管网的试题（选择题）答案
    public static List testGetXgwXztAnswer(String url, Integer page) {
        String index = "信管网参考答案：";
        List answerList = new ArrayList();
        Map<String, Object> answerMap;
        for (int i = 1; i < 76; i++) {
            answerMap = new HashMap<>();
            String realUrl = String.format(url, page);
            ReptileUtils reptileUtils = new ReptileUtils();
            Document doc = reptileUtils.getDocument(realUrl);
            Elements elements1 = doc.select("div.newcon");
            String text = elements1.text();

            //A、B、C
            String multiAnswer = text.substring(text.indexOf(index) + 8, text.indexOf(index) + 13);
            if (multiAnswer.indexOf("、") > 0) {
                String multiAnswer1 = multiAnswer.substring(0, multiAnswer.indexOf("、"));
                answerMap.put("sortNumber", i);
                answerMap.put("answer", multiAnswer1);
                answerList.add(answerMap);

                String multiItem = multiAnswer.substring(multiAnswer.indexOf("、") + 1);
                if (multiItem.indexOf("、") > 0) {
                    String multiAnswer2 = multiItem.substring(0, multiItem.indexOf("、"));

                    answerMap = new HashMap<>();
                    answerMap.put("sortNumber", ++i);
                    answerMap.put("answer", multiAnswer2);
                    answerList.add(answerMap);

                    String multiAnswer3 = multiItem.substring(multiItem.indexOf("、") + 1);
                    answerMap = new HashMap<>();
                    answerMap.put("sortNumber", ++i);
                    answerMap.put("answer", multiAnswer3);
                    answerList.add(answerMap);
                } else {
                    String multiAnswer2 = multiItem.substring(multiItem.indexOf("、") + 1, multiItem.indexOf("、") + 2);
                    answerMap = new HashMap<>();
                    answerMap.put("sortNumber", ++i);
                    answerMap.put("answer", multiAnswer2);
                    answerList.add(answerMap);
                }
            } else {
                String answer = text.substring(text.indexOf(index) + 8, text.indexOf(index) + 9);
                answerMap.put("sortNumber", i);
                answerMap.put("answer", answer);
                answerList.add(answerMap);
            }
            page++;
        }
        return answerList;
    }

    //动态代理ip
    public static List testGetDynamicAgentIp(String url) {
        List list = new ArrayList();
        ReptileUtils reptileUtils = new ReptileUtils();
        Document doc = reptileUtils.getDocument(url);
        Elements table = doc.getElementById("main").getElementsByTag("table");
        Elements trs = table.select("tr");
        for (int i = 1; i < trs.size(); i++) {
            Element tr = trs.get(i);
            Elements tds = tr.select("td");
            Map item = new HashMap();
            for (int j = 0; j < tds.size() - 2; j++) {
                String key = "ip";
                switch (j) {
                    case 0:
                        key = "ip";
                        break;
                    case 1:
                        key = "port";
                        break;
                    case 2:
                        key = "address";
                        break;
                }
                item.put(key, tds.get(j).text());
                list.add(item);
            }
        }
        return list;
    }

    /**
     * telnet 方法
     *
     * @param ip
     * @param port
     * @return
     */
    private static boolean telnet(String ip, int port) {
        Socket s = new Socket();
        try {
            SocketAddress add = new InetSocketAddress(ip, port);
            s.connect(add, 3000);// 超时3秒
            boolean isConnected = s.isConnected();
            s.close();
            return isConnected;
        } catch (IOException e) {
            return false;
        }
    }

    public static void main(String[] args) {
        //testGetXgwXztQuestion("https://www.cnitpm.com/exam/ExamMAM.aspx?sid=291257");
        //List list = testGetXgwXztAnswer("http://www.cnitpm.com/pm1/%s.html", 79369);
        //list.forEach(item -> {
        //    Map answer = (HashMap) item;
        //    System.out.println(answer.get("sortNumber") + ":" + answer.get("answer"));
        //});

        String url = "http://www.66ip.cn/areaindex_19/1.html";
        List<Map> list = testGetDynamicAgentIp(url);
        list.stream().forEach(item -> {
            Object ip = item.get("ip");
            Object port = item.get("port");
            SignInDaily(String.valueOf(ip), Integer.valueOf(String.valueOf(port)));
        });
    }

    /**
     *
     * @return
     */
    private static void SignInDaily(String ip, int port) {
        //记录是否失效
        boolean flag = true;
        try {
            RestTemplate restTemplate = getRestTemplate(ip, port);
            String requestUrl = "https://blog.csdn.net/qq_24101357/article/details/124350135";
            HttpMethod httpMethod = HttpMethod.GET;
            Map<String, Object> paramsMap = new HashMap<>();
            HttpEntity httpEntity = new HttpEntity(paramsMap, null);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (!status.equals(HttpStatus.OK)) {
                flag = false;
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        if (!flag) {
            System.out.println("简爱时光里定时任务，执行失败。");
        } else {
            System.out.println("简爱时光里定时任务，执行成功。");
        }
    }


    public static RestTemplate getRestTemplate(String ip, int port) throws Exception {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
        //设置代理端口和不进行重点向跳转
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().disableRedirectHandling()
                .setProxy(new HttpHost(ip, port, "http"));
        httpClientBuilder.setSSLSocketFactory(socketFactory);
        HttpClient httpClient = httpClientBuilder.build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(httpClient);
        factory.setReadTimeout(10000);
        factory.setConnectTimeout(10000);
        return new RestTemplate(factory);
    }

}
